import request from '@/utils/request'

/**
 * API服务类 - 统一管理所有API调用
 */
class ApiService {
  constructor() {
    this.baseURL = import.meta.env.VITE_APP_BASE_API || 'http://localhost:8080'
  }

  // ==================== 认证相关 ====================
  
  // 登录
  async login(credentials) {
    try {
      const response = await request({
        url: '/auth/login',
        method: 'post',
        data: credentials
      })
      
      // 保存token和用户信息
      if (response.data && response.data.accessToken) {
        localStorage.setItem('token', response.data.accessToken)
        localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))
      }
      
      return response
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 获取用户信息
  async getUserInfo() {
    try {
      const response = await request({
        url: '/auth/info',
        method: 'get'
      })
      
      // 更新本地用户信息
      if (response.data) {
        localStorage.setItem('userInfo', JSON.stringify(response.data))
      }
      
      return response
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 退出登录
  async logout() {
    try {
      await request({
        url: '/auth/logout',
        method: 'post'
      })
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }

  // ==================== 商家相关 ====================
  
  // 获取商家信息
  async getMerchantInfo() {
    return await request({
      url: '/merchant/info',
      method: 'get'
    })
  }

  // 更新商家信息
  async updateMerchantInfo(data) {
    return await request({
      url: '/merchant/info',
      method: 'put',
      data
    })
  }

  // ==================== 订单相关 ====================
  
  // 获取订单列表
  async getOrders(params) {
    return await request({
      url: '/orders',
      method: 'get',
      params
    })
  }

  // 获取订单详情
  async getOrderDetail(id) {
    return await request({
      url: `/orders/${id}`,
      method: 'get'
    })
  }

  // 更新订单状态
  async updateOrderStatus(id, status, data = {}) {
    return await request({
      url: `/orders/${id}/status`,
      method: 'put',
      data: { status, ...data }
    })
  }

  // ==================== 商品相关 ====================
  
  // 获取商品列表
  async getGoods(params) {
    return await request({
      url: '/merchant/goods',
      method: 'get',
      params
    })
  }

  // 获取商品详情
  async getGoodsDetail(id) {
    return await request({
      url: `/merchant/goods/${id}`,
      method: 'get'
    })
  }

  // 创建商品
  async createGoods(data) {
    return await request({
      url: '/merchant/goods',
      method: 'post',
      data
    })
  }

  // 更新商品
  async updateGoods(id, data) {
    return await request({
      url: `/merchant/goods/${id}`,
      method: 'put',
      data
    })
  }

  // 删除商品
  async deleteGoods(id) {
    return await request({
      url: `/merchant/goods/${id}`,
      method: 'delete'
    })
  }

  // ==================== 洗护服务相关 ====================
  
  // 获取洗护服务列表
  async getLaundryServices(params) {
    return await request({
      url: '/laundry/services',
      method: 'get',
      params
    })
  }

  // 获取洗护订单列表
  async getLaundryOrders(params) {
    return await request({
      url: '/laundry/orders',
      method: 'get',
      params
    })
  }

  // 更新洗护订单状态
  async updateLaundryOrderStatus(id, status, data = {}) {
    return await request({
      url: `/laundry/orders/${id}/status`,
      method: 'put',
      data: { status, ...data }
    })
  }

  // ==================== 仪表板相关 ====================
  
  // 获取仪表板概览数据
  async getDashboardOverview() {
    return await request({
      url: '/dashboard/overview',
      method: 'get'
    })
  }

  // 获取统计数据
  async getStatistics(type, params = {}) {
    return await request({
      url: `/dashboard/statistics/${type}`,
      method: 'get',
      params
    })
  }

  // ==================== 优惠券相关 ====================
  
  // 获取优惠券列表
  async getCoupons(params) {
    return await request({
      url: '/coupons',
      method: 'get',
      params
    })
  }

  // 创建优惠券
  async createCoupon(data) {
    return await request({
      url: '/coupons',
      method: 'post',
      data
    })
  }

  // ==================== 文件上传 ====================
  
  // 上传文件
  async uploadFile(file, type = 'image') {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', type)
    
    return await request({
      url: '/upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  // ==================== 通用方法 ====================
  
  // 检查服务器连接
  async checkConnection() {
    try {
      const response = await request({
        url: '/test/health',
        method: 'get',
        timeout: 5000
      })
      return response.code === 200
    } catch (error) {
      console.error('服务器连接检查失败:', error)
      return false
    }
  }

  // 获取系统配置
  async getSystemConfig() {
    return await request({
      url: '/system/config',
      method: 'get'
    })
  }
}

// 创建单例实例
const apiService = new ApiService()

export default apiService
